//获取应用实例
var app = getApp();

var FormCheckRule = {
    idCardRule1: /^[0-9]{14}([0-9]|X|x)$/,
    idCardRule2: /^[0-9]{17}([0-9]|X|x)$/,
    nameRule: /^[^ ]{2,60}$/,
    telRule: /^[1]{1}[0-9]{10}$/,
    urgentApplicantNullMessage: "请输入车主名称！",
    urgentApplicantErrorMessage: "请输入正确的车主名称！",
    typeSelection: "请选择车辆类型！",
    cardPlateNullMessage: "请输入车牌号码！",
    cardPlateErrorMessage: "请输入正确的车牌号码！",
    cardNbrNullMessage: "请输入缴款流水号！",
    cardNbrErrorMessage: "请输入正确的缴款流水号！",
    cardErrorMessage: "请扫描正确的缴款流水号！",
    handleNullMessage: "请选择办理类型！",
    vehicleNullMessage: "请选择办理站点！",
    contactNameNullMessage:"请输入收件人姓名！",
    contactNameErrorMessage:"请输入正确的收件人姓名！",
    cellNumNullMessage:"请输入收件人电话！",
    cellNumErrorMessage:"请输入正确的收件人电话！",
    areaNameNullMessage:"请选择所在地区！",
    streetNullMessage:"请输入详细地址！",
    streetMinNullMessage:"详细地址不能小于5个字符！",
    checkService:"请阅读并同意《行驶证邮寄服务协议》"
};

Page({
    data: {
        isShowPayMent: false, //缴款实例图
        processList: [ //办理进度信息
            {text: '车管所办理'},{text: '办理邮寄'},{text: '等待制证'},{text: '送证上门'}
        ],

        carTypeList:[], //车辆类型
        typeSelectionText: "请选择车辆类型",
        typeSelectionCode: '',
        typeStyle: 0,  //点击后颜色的状态

        handleTypeList: [], //办理类型
        handleStyle: 0,
        handleSelectionText: '请选择办理的类型', //办理类型默认数据

        vehicleStyle: 0, //办理车管所
        vehicleSelectionText: '请选择办理的站点', //车管所默认数据
        carOfficeNameList: [],

        showView: false, //车牌前缀
        showViewList: false, //车辆列表
        items:[
            {userId: 1, name: "京"}, {userId: 2, name: "津"}, {userId: 3, name: "沪"}, {userId: 4, name: "渝"}, {userId: 5, name: "湘"}, {userId: 6, name: "黑"}, {userId: 7, name: "琼"},
            {userId: 8, name: "贵"}, {userId: 9, name: "苏"}, {userId: 10, name: "闽"}, {userId: 11, name: "辽"}, {userId: 12, name: "宁"}, {userId: 13, name: "粤"}, {userId: 14, name: "陕"},
            {userId: 15, name: "豫"}, {userId: 16, name: "新"}, {userId: 17, name: "赣"}, {userId: 18, name: "冀"}, {userId: 19, name: "甘"}, {userId: 20, name: "鄂"}, {userId: 21, name: "吉"},
            {userId: 22, name: "浙"}, {userId: 23, name: "云"}, {userId: 24, name: "桂"}, {userId: 25, name: "皖"}, {userId: 26, name: "晋"}, {userId: 27, name: "鲁"}, {userId: 28, name: "川"},
            {userId: 29, name: "蒙"}, {userId: 30, name: "藏"}, {userId:31, name: "青"}
        ],
       

        //输入框默认值
        cardNbr:"",   //缴纳流水号
        userCellName: "",  //车牌前缀
        cardFix: "", //车牌号码
        recipientName: "", //收件人姓名
      
        isShowFootNav:true,
        isFromScanCode:false,
        isCanScroll:true,
        userCellId: 0,
        cardNbrIconType: "",
        cardFixIconType: "",
        cardApplicant: "",
        recipientNameType: "",
        contactNumberType: "",

        //省，市，区选择
        area:"请选择所在地区",
        areaStyle:"color: #B2B2B2;font-size:34rpx",
        cardNbrStyle:"",
        isNoticeShow:false,  //服务协议说明
        needInvoice:0,  //是否勾选
        num: 0
    },

    getDrivingInformation() {
        let that = this;
        let opt = {
            url: app.globalData.host+"/wx/di/sd.ajax",
            data: {},
            sucFn:function (result) {
                let res = result.body;
                that.setData({
                    carTypeList: res.carTypeList, //车辆类型
                    handleTypeList: res.handleTypeList, //办理类型
                    carOfficeNameList: res.carOfficeNameList, //车管所
                    carNbrPrefixList: res.carNbrPrefixList,  //车牌前缀
                    userCellName: res.carNbrPrefixList[0].value  //默认取第一个字段
                })
               console.log(result)
            }
        };
        app.ajax(opt);
    },
    onLoad: function (options) {
        // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
        app.globalData.channelId = decodeURIComponent(options.scene)=='undefined'?'':decodeURIComponent(options.scene);
        console.log("channelId",app.globalData.channelId);

        this.getDrivingInformation()
        app.initAddress();
    },
    bindStop:function(event){

    },
    //分享功能
    onShareAppMessage:function () {
        return {
            title: '行驶证邮寄服务',
            desc: '行驶证邮寄服务!',
            path: '/pages/handle/handle'
        }
    },
    cacheData:function () {
        app.setStorageSync(app.globalData.cacheTravelData,Object.assign({},this.data,{ popErrorMsg: '' },{errorScrollIntoViewName: ''},
        {errorFocusName:''}, {isCanScroll: true})); //保存状态在缓存

        app.removeStorageSync('arriveSuccess') //清除到达成功页标识
    },
    onHide:function () {
        this.cacheData()
    },
    onUnload:function(){
        this.cacheData()
    },
    onShow:function () {
        app.authAjax();
        var page = app.getStorageSync(app.globalData.cacheTravelData);
        let cardNbr = !app.getStorageSync('arriveSuccess')?this.data.cardNbr:'';
        this.setData(Object.assign({},page,{cardNbr: cardNbr})); //缓存赋值

    },

    //底部切换页面方法
    toUrl(e) {
        var url = e.currentTarget.dataset.url;
        if(url!='/pages/travelHandle/travelHandle'){
            if(url == ''){
                var res = {
                    appid:app.globalData.appid,
                    path: app.globalData.path,
                    envVersion: app.globalData.envVersion
                }
                app.crossToUrl(res)
            }else {
                app.redirectTo({url: url});
            }
        }
    },

    showAbout(e) { //缴款示例图
        this.setData({
            isShowPayMent: true,
            isShowFootNav: false
        })
    },

    hideAbout() {
        this.setData({
            isShowPayMent: false,
            isShowFootNav: true
        })
    },
    //确认提交按钮
    formSubmit(e) {
        let formData = e.detail.value,
            cardNbr = formData.cardNbr,
            cardFix = formData.cardFix,
            cardApplicant = formData.cardApplicant,
            recipientName = formData.recipientName,
            cardNumber = formData.cardNumber,
            street = formData['address.street'],
            provinceId = formData['address.provinceId'],
            needInvoice = formData.needInvoice,
            pageObj = this;
        let flag = app.check([
            { //车主姓名
                value: cardApplicant,
                errorFocusName:"applicant",
                errorScrollIntoViewName:"signProcess",
                fn: function (value) {
                    if(value == ''){
                        app.errorToast(FormCheckRule.urgentApplicantNullMessage);
                    }else if(FormCheckRule.nameRule.test(value)){
                        return true;
                    }else {
                        app.errorToast(FormCheckRule.urgentApplicantErrorMessage);
                    }
                }
            },{
            	value: this.data["typeStyle"],
                errorScrollIntoViewName:"signProcess",
            	fn: function (value) {
            		if(value == '0'){
            			app.errorToast(FormCheckRule.typeSelection);
            		}else {
            			return true;
            		}
            	}
            },{
            	value: cardFix,
            	errorFocusName:"cardFix",
                errorScrollIntoViewName:"signProcess",
            	fn: function (value) {
                    console.log(value)
            		if(value.length == 5||value.length == 6){
            			return true;
            		}else if(value == ''){
                        app.errorToast(FormCheckRule.cardPlateNullMessage);
            			return false;
            		}else {
            			app.errorToast(FormCheckRule.cardPlateErrorMessage);
            		}
            	}
            },{
                value: cardNbr,
                errorFocusName:"cardNbr",
                errorScrollIntoViewName:"cardFixView",
                fn: function(value){
                    if(value == ''){
                        app.errorToast(FormCheckRule.cardNbrNullMessage);
                        return false;
                    }else if(value.length > 1){
                        return true;
                    }else {
                        app.errorToast(FormCheckRule.cardNbrErrorMessage);
                    }
                }
            },{
                value: this.data['handleStyle'],
                errorScrollIntoViewName:"cardNbrView",
                fn: function (value) {
                    if(value == '0'){
                        app.errorToast(FormCheckRule.handleNullMessage);
                    }else {
                        return true;
                    }
                }
            },{
                value: this.data['vehicleStyle'],
                errorScrollIntoViewName:"cardNbrView",
                fn: function (value) {
                    if(value == '0'){
                        app.errorToast(FormCheckRule.vehicleNullMessage);
                    }else {
                        return true;
                    }
                }
            },{
                value: recipientName,
                errorFocusName:"recipientName",
                errorScrollIntoViewName:"carTypeView",
                fn: function (value) {
                    if(value == ''){
                        app.errorToast(FormCheckRule.contactNameNullMessage);
                    }else if(FormCheckRule.nameRule.test(value)){
                        return true;
                    }else {
                        app.errorToast(FormCheckRule.contactNameErrorMessage);
                    }
                }
            },{
                value: cardNumber,
                errorFocusName:"contactNumber",
                errorScrollIntoViewName:"carTypeView",
                fn: function(value){
                    if(value == ''){
                        app.errorToast(FormCheckRule.cellNumNullMessage);
                    }else if(FormCheckRule.telRule.test(value)){
                        return true;
                    }else {
                        app.errorToast(FormCheckRule.cellNumErrorMessage);
                    }
                }
            },{
                value: provinceId,
                errorFocusName:"provinceId",
                errorScrollIntoViewName:"cardNumberView",
                rule: app.globalData.Rule.required,
                fn: function (value) {
                    if(value!=''){
                        return true;
                    }else{
                        app.errorToast(FormCheckRule.areaNameNullMessage);
                        return false
                    }
                }
            },{
                value: street,
                errorFocusName:"street",
                errorScrollIntoViewName:"areaView",
                fn: function(value){
                    if(value ==''){
                        app.errorToast(FormCheckRule.streetNullMessage);
                    }else if(value.length<5) {
                        app.errorToast(FormCheckRule.streetMinNullMessage);
                    }else {
                        return true;
                    }
                }
            }
        ]);

        if (!flag) {
            return false;
        }
        if(needInvoice==0){
            app.errorToast(FormCheckRule.checkService);
            return false;
        }
        if(app.globalData.openId==''||app.globalData.openId==null||app.globalData.openId=="null"){
            app.toastAuthFailModal();
            return false;
        }
        var postData = formData;
        var res = this.data;
        postData['address.fullAddr'] = formData['address.provinceName']+formData['address.cityName']+formData['address.countyName']+street;

        postData['cardName'] = res.applicant;  //车主姓名
        postData['carType'] = res.typeSelectionCode;  //车辆类型
        postData['carNbr'] = res.cardFix? '粤' + res.userCellName+res.cardFix:'';  //车牌号码
        postData['payNbr'] = res.cardNbr;  //缴款流水号
        postData['handleType'] = res.handleSelectionCode  //办理类型
        postData['carOfficeName'] = res.vehicleSelectionCode  //车管所名称
        postData['address.cellNum'] = formData.cardNumber;
        postData['address.contactName'] = formData.recipientName;
        postData['certPlaceProvinceId'] = '440000';
        postData['certPlaceCityId'] = '440600';
        postData['certPlaceName'] = '广东省佛山市';
        console.log(postData)
        
        var opt = {
            url: app.globalData.host+"/wx/di/handling.ajax",
            data: postData,
            sucFn:function (result) {
                postData['payType'] = result.body.payType; //支付类型
                postData['typeSelectionText'] = res.typeSelectionText; //车辆类型
                postData['handleSelectionText'] = res.handleSelectionText;  //办理类型
                postData['serviceFee_cn'] = result.body.serviceFee;  //服务费
                postData['totalChargeFee_cn'] = result.body.totalChargeFee; //总费用
                postData['totalFee_cn'] = result.body.totalFee;
                postData['cardFix'] = res.cardFix;
                app.setStorageSync(app.globalData.cacheTravelOrderPay, postData);
                app.navigateTo({url:'../travelPayment/travelPayment'})
            }
        };
        app.ajax(opt);
    },

    //说明内容
    agreeTap:function (e) {
        app.navigateTo({url: '../travelNotice/travelNotice'});
    },
    //隐藏说明内容
    noticeKnowTap:function (e) {
        this.setData({
            isNoticeShow:false,
            isShowFootNav: true
        });
    },
    areaTap:function (e) {
        this.setData({
            isAddressShow: true,
            isShowFootNav: false
        });
    },

    //条形码
    bindViewTap: function() {
        var that = this;
        var path= /^[0-9a-zA-Z]*$/g;
        wx.scanCode({
            // onlyFromCamera: true,
            success: function(res){
                if(path.test(res.result)){
                    that.setData({
                        cardNbr: res.result,
                    });
                }else {
                    app.errorToast(FormCheckRule.cardErrorMessage);
                }
            }
        })
    },
    //车牌前缀
    userListAction:function(e){
        this.setData({
            userCellName: e.target.dataset.name,
            showView: false,
            isShowFootNav: true
        })
    },

    //点击车牌前缀
    provinceName: function(e){
        this.setData({
            showView: true,
            isShowFootNav:false
        })
    },

    //输入框公用方法
    infoInput: function(e){
        var id = e.currentTarget.id,
            value = e.detail.value.replace(/(^\s*)|(\s*$)/g,"");

        if(id == "applicant"){
            this.setData({applicant: value});
            if(value==''){
                this.setData({cardNameIconType: "success"});
            }else if(FormCheckRule.nameRule.test(value)){
                this.setData({cardNameIconType: "success"});
            } else if(value.length>0){
                this.setData({cardNameIconType: "error"});
            }else {
                this.setData({
                    cardNameIconType: "",
                    applicant: value
                });
            }
        }else if(id == "cardNbr"){ 
            var pattern = /([^0-9]|\s)*/g,
                that = this;
                value = value.replace(pattern, '');
                that.setData({"cardNbr": value});
            if(value==''){
                this.setData({acceptanceIconType: "success"});
            }else if(value.length==1){
                this.setData({acceptanceIconType: "error"});
            }else {
                this.setData({acceptanceIconType: "success"});
            }
        }else if(id == "recipientName"){
            this.setData({recipientName: value});
            if(value==''){
                this.setData({recipientNameIconType: "success"});
            }else if (FormCheckRule.nameRule.test(value)) {
                this.setData({recipientNameIconType: "success"});
            } else if (value.length > 0) {
                this.setData({recipientNameIconType: "error"});
            }else {
                this.setData({recipientNameIconType: ""});
            }
        }else if(id == "contactNumber"){
            value = value.substr(0, 11);
            this.setData({contactNumber: value});
            if(value==''){
                this.setData({urgentLinkTelIconType: "success"});
            }else if (FormCheckRule.telRule.test(value)) {
                this.setData({urgentLinkTelIconType: "success"});
            } else if (value.length > 0) {
                this.setData({urgentLinkTelIconType: "error"});
            } else {
                this.setData({urgentLinkTelIconType: ""});
            }

        }else if(id == "address.street"){
            this.setData({"address.street": value});
            if(value==''){
                this.setData({streetNameIconType: "success"});
            }else if(value.length>4){
                this.setData({streetNameIconType: "success"});
            } else if(value.length>0){
                this.setData({streetNameIconType: "error"})
            }else {
                this.setData({streetNameIconType: ""})
            }
        }

    },

    //是否勾选
    checkTap:function (e) {
        var needInvoice = e.target.dataset.agree;
        if(needInvoice==0){
            needInvoice = 1;
        }else{
            needInvoice = 0;
        }
        this.setData({needInvoice: needInvoice});
    },
    //车牌号码只能输入大写
    infoProFix: function(e){
        //var pattern = /([^A-Za-z0-9]{5,6}[a-zA-Z0-9\u4E00-\u9FA5]{1,2}|\s)*/g,

        // var pattern = /([^A-Za-z0-9]|\s)*/g,
        var value = e.detail.value.replace(/(^\s*)|(\s*$)/g,""),
            that = this;
        if(value == ''){
            this.setData({cardNbrIconType: "success"});
        }else if(value.length == 5||value.length == 6){
            this.setData({cardNbrIconType: "success"});
        }else if(value.length>0){
            this.setData({cardNbrIconType: "error"});
        }

        this.setData({
            cardFix: value.replace("I", 1).replace("O", 0).toUpperCase()
        });
    },

    //显示车辆类型列表 start
    typeSelection: function(e){
        var that = this;
        setTimeout(function(){
            that.setData({
                isCanScroll:false,
                showViewList: true,
                isShowFootNav: false
            });
        },100)

    },

    hideSelection: function(){
        this.setData({
            isCanScroll:true,
            showViewList: false,
            isShowFootNav: true
        });
    },

    //选择车辆类型列表 end
    showViewList: function(e){
        this.setData({
            isCanScroll:true,
            showViewList: false,
            typeStyle: 1,
            typeSelectionText: e.target.dataset.name,
            typeSelectionCode: e.target.dataset.code,
            isShowFootNav: true
        });
    },

    // 办理类型 start
    handleSelection() {
        this.setData({
            isCanScroll:false,
            showHandleList: true,
            isShowFootNav: false
        })
    },

    hideHandleSelection: function(){
        this.setData({
            isCanScroll:true,
            showHandleList: false,
            isShowFootNav: true
        });
    },

    checkHandleContent: function(e){
        this.setData({
            isCanScroll:true,
            showHandleList: false,
            handleStyle: 1,
            handleSelectionText: e.target.dataset.name,
            handleSelectionCode: e.target.dataset.code,
            isShowFootNav: true
        });
    },
    //办理类型 end

    // 办理类型 start
    vehicleSelection() {
        this.setData({
            isCanScroll:false,
            showVehicleList: true,
            isShowFootNav: false
        })
    },

    hideVehicleSelection: function(){
        this.setData({
            isCanScroll:true,
            showVehicleList: false,
            isShowFootNav: true
        });
    },

    checkVehicleContent: function(e){
        this.setData({
            isCanScroll:true,
            showVehicleList: false,
            vehicleStyle: 1,
            vehicleSelectionText: e.target.dataset.name,
            vehicleSelectionCode: e.target.dataset.code,
            isShowFootNav: true
        });
    },
    //办理类型 end

    //选择城市取消按钮
    cancelAddressTap:function (e) {
        this.setData({
            isAddressShow: false,
            isShowFootNav: true
        });
    },
    //选择城市确定按钮
    confirmAddressTap:function (e) {
        var current_value = this.data.value;
        var provinceName = this.data.proviceData[current_value[0]].name;
        var cityName = this.data.cityData[current_value[1]].name;
        var countyName = "";
        if(this.data.districtData[current_value[2]].name!=null){
            countyName = this.data.districtData[current_value[2]].name;
        }
        this.setData({
            isShowFootNav:true,
            isAddressShow: false,
            areaStyle:"color:#1a1a1a;font-size:34rpx",
            area:provinceName+cityName+countyName,
            "address.provinceId":this.data.proviceData[current_value[0]].id,
            "address.cityId":this.data.cityData[current_value[1]].id,
            "address.countyId":this.data.districtData[current_value[2]].id,
            "address.provinceName":provinceName,
            "address.cityName":cityName,
            "address.countyName":countyName
        });
    },
    //省市区滑动事件
    bindAddressChange: function (e) {
        app.bindAddressChange(e);
    }

});
